# -*- coding: utf-8 -*-
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
reload(sys)
sys.setdefaultencoding("utf-8")

HOST = "smtp.163.com"


def addimg(src, imgid):  # 添加图片函数,参数1：图片路径，参数2：图片id
    fp = open(src, 'rb')  # 打开文件
    msgImage = MIMEImage(fp.read())  # 创建MIMEImage对象，读取图片内容作为参数
    fp.close()  # 关闭文件
    msgImage.add_header('Content-ID', imgid)  # 指定图片文件的Content-ID,<img>
    # 标签src用到
    return msgImage  # 返回msgImage对象


def send_file_email(where, what, file_name, subject, to='354217718@qq.com'):
    SUBJECT = subject
    TO = to
    FROM = where
    msg = MIMEMultipart('related')  # 创建MIMEMultipart对象，采用related定义内嵌资源
    # 的邮件体
    # 创建一个MIMEText对象，HTML元素包括文字与图片<img>
    msgtext = MIMEText(what,
                       "html",
                       "utf-8")
    msg.attach(msgtext)  # MIMEMultipart对象附加MIMEText的内容
    # msg.attach(addimg("1.JPG", "weekly"))  # 使用MIMEMultipart对象附加
    # MIMEImage的内容

    # 创建一个MIMEText对象，附加week_report.xlsx文档
    attach = MIMEText(open(file_name, "rb").read(), "base64", "utf-8")
    attach["Content-Type"] = "application/octet-stream"  # 指定文件格式类型
    # 指定Content-Disposition值为attachment则出现下载保存对话框，保存的默认文件名使用
    # filename指定
    # 由于qqmail使用gb18030页面编码，为保证中文文件名不出现乱码，对文件名进行编码转换
    attach["Content-Disposition"] = "attachment; filename=\""+file_name+"\"".decode("utf-8").encode("gb18030")

    msg.attach(attach)  # MIMEMultipart对象附加MIMEText附件内容
    msg['Subject'] = SUBJECT
    msg['From'] = FROM
    msg['To'] = TO
    try:
        server = smtplib.SMTP()
        server.connect(HOST, "25")
        server.starttls()
        server.login("15238356618@163.com", "han15238356618")
        server.sendmail(FROM, TO, msg.as_string())
        server.quit()
        print "邮件发送成功！"
    except Exception, e:
        print "失败：" + str(e)
